/* USER CODE BEGIN Header */
/**
  ******************************************************************************
  * @file    usart.c
  * @brief   This file provides code for the configuration
  *          of the USART instances.
  ******************************************************************************
  * @attention
  *
  * Copyright (c) 2023 STMicroelectronics.
  * All rights reserved.
  *
  * This software is licensed under terms that can be found in the LICENSE file
  * in the root directory of this software component.
  * If no LICENSE file comes with this software, it is provided AS-IS.
  *
  ******************************************************************************
  */
/* USER CODE END Header */
/* Includes ------------------------------------------------------------------*/
#include "usart.h"

/* USER CODE BEGIN 0 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "globles.h"
#include "cmsis_os.h"
#include "task.h"
#include "car.h"

#define UART_QUEUE_SIZE 32 

char g_uart1_rx_buf[1];
char g_uart2_rx_buf[1];

UART_Queue *g_uart1_rx_queue;
UART_Queue *g_uart2_rx_queue;

UART_Queue *createQueue(int size);
void destroyQueue(UART_Queue *q);
void enqueue(UART_Queue *q, char c);
char dequeue(UART_Queue *q);
int isEmpty(UART_Queue *q);
int isFull(UART_Queue *q);
/* USER CODE END 0 */

UART_HandleTypeDef huart1;
UART_HandleTypeDef huart2;

/* USART1 init function */

void MX_USART1_UART_Init(void)
{

  /* USER CODE BEGIN USART1_Init 0 */

  /* USER CODE END USART1_Init 0 */

  /* USER CODE BEGIN USART1_Init 1 */

  /* USER CODE END USART1_Init 1 */
  huart1.Instance = USART1;
  huart1.Init.BaudRate = 115200;
  huart1.Init.WordLength = UART_WORDLENGTH_8B;
  huart1.Init.StopBits = UART_STOPBITS_1;
  huart1.Init.Parity = UART_PARITY_NONE;
  huart1.Init.Mode = UART_MODE_TX_RX;
  huart1.Init.HwFlowCtl = UART_HWCONTROL_NONE;
  huart1.Init.OverSampling = UART_OVERSAMPLING_16;
  if (HAL_UART_Init(&huart1) != HAL_OK)
  {
    Error_Handler();
  }
  /* USER CODE BEGIN USART1_Init 2 */
  HAL_UART_Receive_IT(&huart1, (uint8_t*)g_uart1_rx_buf, 1);
  g_uart1_rx_queue = createQueue(UART_QUEUE_SIZE);
  if (g_uart1_rx_queue == NULL)
  {
    Error_Handler();
  }

  /* USER CODE END USART1_Init 2 */

}
/* USART2 init function */

void MX_USART2_UART_Init(void)
{

  /* USER CODE BEGIN USART2_Init 0 */

  /* USER CODE END USART2_Init 0 */

  /* USER CODE BEGIN USART2_Init 1 */

  /* USER CODE END USART2_Init 1 */
  huart2.Instance = USART2;
  huart2.Init.BaudRate = 9600;
  huart2.Init.WordLength = UART_WORDLENGTH_8B;
  huart2.Init.StopBits = UART_STOPBITS_1;
  huart2.Init.Parity = UART_PARITY_NONE;
  huart2.Init.Mode = UART_MODE_TX_RX;
  huart2.Init.HwFlowCtl = UART_HWCONTROL_NONE;
  huart2.Init.OverSampling = UART_OVERSAMPLING_16;
  if (HAL_UART_Init(&huart2) != HAL_OK)
  {
    Error_Handler();
  }
  /* USER CODE BEGIN USART2_Init 2 */
  HAL_UART_Receive_IT(&huart2, (uint8_t*)g_uart2_rx_buf, 1);
  g_uart2_rx_queue = createQueue(UART_QUEUE_SIZE);
  if (g_uart2_rx_queue == NULL)
  {
    Error_Handler();
  }
  
  /* USER CODE END USART2_Init 2 */

}

void HAL_UART_MspInit(UART_HandleTypeDef* uartHandle)
{

  GPIO_InitTypeDef GPIO_InitStruct = {0};
  if(uartHandle->Instance==USART1)
  {
  /* USER CODE BEGIN USART1_MspInit 0 */

  /* USER CODE END USART1_MspInit 0 */
    /* USART1 clock enable */
    __HAL_RCC_USART1_CLK_ENABLE();

    __HAL_RCC_GPIOA_CLK_ENABLE();
    /**USART1 GPIO Configuration
    PA9     ------> USART1_TX
    PA10     ------> USART1_RX
    */
    GPIO_InitStruct.Pin = GPIO_PIN_9;
    GPIO_InitStruct.Mode = GPIO_MODE_AF_PP;
    GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_HIGH;
    HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);

    GPIO_InitStruct.Pin = GPIO_PIN_10;
    GPIO_InitStruct.Mode = GPIO_MODE_INPUT;
    GPIO_InitStruct.Pull = GPIO_NOPULL;
    HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);

    /* USART1 interrupt Init */
    HAL_NVIC_SetPriority(USART1_IRQn, 7, 0);
    HAL_NVIC_EnableIRQ(USART1_IRQn);
  /* USER CODE BEGIN USART1_MspInit 1 */

  /* USER CODE END USART1_MspInit 1 */
  }
  else if(uartHandle->Instance==USART2)
  {
  /* USER CODE BEGIN USART2_MspInit 0 */

  /* USER CODE END USART2_MspInit 0 */
    /* USART2 clock enable */
    __HAL_RCC_USART2_CLK_ENABLE();

    __HAL_RCC_GPIOA_CLK_ENABLE();
    /**USART2 GPIO Configuration
    PA2     ------> USART2_TX
    PA3     ------> USART2_RX
    */
    GPIO_InitStruct.Pin = GPIO_PIN_2;
    GPIO_InitStruct.Mode = GPIO_MODE_AF_PP;
    GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_HIGH;
    HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);

    GPIO_InitStruct.Pin = GPIO_PIN_3;
    GPIO_InitStruct.Mode = GPIO_MODE_INPUT;
    GPIO_InitStruct.Pull = GPIO_NOPULL;
    HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);

    /* USART2 interrupt Init */
    HAL_NVIC_SetPriority(USART2_IRQn, 6, 0);
    HAL_NVIC_EnableIRQ(USART2_IRQn);
  /* USER CODE BEGIN USART2_MspInit 1 */

  /* USER CODE END USART2_MspInit 1 */
  }
}

void HAL_UART_MspDeInit(UART_HandleTypeDef* uartHandle)
{

  if(uartHandle->Instance==USART1)
  {
  /* USER CODE BEGIN USART1_MspDeInit 0 */

  /* USER CODE END USART1_MspDeInit 0 */
    /* Peripheral clock disable */
    __HAL_RCC_USART1_CLK_DISABLE();

    /**USART1 GPIO Configuration
    PA9     ------> USART1_TX
    PA10     ------> USART1_RX
    */
    HAL_GPIO_DeInit(GPIOA, GPIO_PIN_9|GPIO_PIN_10);

    /* USART1 interrupt Deinit */
    HAL_NVIC_DisableIRQ(USART1_IRQn);
  /* USER CODE BEGIN USART1_MspDeInit 1 */
    destroyQueue(g_uart1_rx_queue);
    g_uart1_rx_queue = NULL;
  /* USER CODE END USART1_MspDeInit 1 */
  }
  else if(uartHandle->Instance==USART2)
  {
  /* USER CODE BEGIN USART2_MspDeInit 0 */

  /* USER CODE END USART2_MspDeInit 0 */
    /* Peripheral clock disable */
    __HAL_RCC_USART2_CLK_DISABLE();

    /**USART2 GPIO Configuration
    PA2     ------> USART2_TX
    PA3     ------> USART2_RX
    */
    HAL_GPIO_DeInit(GPIOA, GPIO_PIN_2|GPIO_PIN_3);

    /* USART2 interrupt Deinit */
    HAL_NVIC_DisableIRQ(USART2_IRQn);
  /* USER CODE BEGIN USART2_MspDeInit 1 */
    destroyQueue(g_uart2_rx_queue);
    g_uart2_rx_queue = NULL;
  /* USER CODE END USART2_MspDeInit 1 */
  }
}

/* USER CODE BEGIN 1 */
/* 加入以下代码, 支持printf函数, 而不�??????要�?�择use MicroLIB */

#if 1
#if (__ARMCC_VERSION >= 6010050)                    /* 使用AC6编译器时 */
__asm(".global __use_no_semihosting\n\t");          /* 声明不使用半主机模式 */
__asm(".global __ARM_use_no_argv \n\t");            /* AC6下需要声明main函数为无参数格式，否则部分例程可能出现半主机模式 */

#else
/* 使用AC5编译器时, 要在这里定义__FILE �?????? 不使用半主机模式 */
#pragma import(__use_no_semihosting)

struct __FILE
{
    int handle;
    /* Whatever you require here. If the only file you are using is */
    /* standard output using printf() for debugging, no file handling */
    /* is required. */
};

#endif

/* 不使用半主机模式，至少需要重定义_ttywrch\_sys_exit\_sys_command_string函数,以同时兼容AC6和AC5模式 */
int _ttywrch(int ch)
{
    ch = ch;
    return ch;
}

/* 定义_sys_exit()以避免使用半主机模式 */
void _sys_exit(int x)
{
    x = x;
}

char *_sys_command_string(char *cmd, int len)
{
    return NULL;
}

/* FILE �?????? stdio.h里面定义. */
FILE __stdout;

/* 重定义fputc函数, printf函数�??????终会通过调用fputc输出字符串到串口 */
int fputc(int ch, FILE *f)
{
    /* 等待上一个字符发送完�?????? */
    while ((__HAL_UART_GET_FLAG(&huart1, UART_FLAG_TC) ? SET : RESET) == RESET);
      
    /* 将要发�?�的字符 ch 写入到DR寄存�?????? */
    huart1.Instance->DR = (uint8_t)ch;
    return ch;
}
#endif

UART_Queue *createQueue(int size)
{
  UART_Queue *q = (UART_Queue *)malloc(sizeof(UART_Queue));
  if (!q)
  {
    return NULL;
  }

  q->buffer = (char *)malloc(sizeof(char) * size);
  if (!q->buffer)
  {
    free(q);
    return NULL;
  }

  q->head = 0;
  q->tail = 0;
  q->size = size;
  return q;
}

void destroyQueue(UART_Queue *q)
{
  if (!q)
  {
    return;
  }
  
  free(q->buffer);
  free(q);
}

void enqueue(UART_Queue *q, char c)
{
  if (isFull(q)) {
    return;
  }

  q->buffer[q->tail] = c;
  q->tail = (q->tail + 1) % q->size;
}

char dequeue(UART_Queue *q)
{
  char c = q->buffer[q->head];
  q->head = (q->head + 1) % q->size;
  return c;
}

int isEmpty(UART_Queue *q)
{
  return q->head == q->tail;
}

int isFull(UART_Queue *q)
{
  return ((q->tail + 1) % q->size) == q->head;
}

char UART1_Dequeue(void)
{
  if (isEmpty(g_uart1_rx_queue)) 
  {
    return 0;
  }

  return dequeue(g_uart1_rx_queue);
}

char UART2_Dequeue(void)
{
  if (isEmpty(g_uart2_rx_queue)) 
  {
    return 0;
  }

  return dequeue(g_uart2_rx_queue);
}

/* 串口数据接收完成回调函数 */
void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart)
{
  BaseType_t xHigherPriorityTaskWoken;

  if (huart->Instance == USART1)
  {
    enqueue(g_uart1_rx_queue, g_uart1_rx_buf[0]);

    xTaskNotifyFromISR((TaskHandle_t)uartTaskHandle,
                       (uint32_t)UART1_EVT,
                       (eNotifyAction)eSetBits,
                       &xHigherPriorityTaskWoken);
    portYIELD_FROM_ISR(xHigherPriorityTaskWoken);
  }
  else if (huart->Instance == USART2)
  {
    enqueue(g_uart2_rx_queue, g_uart2_rx_buf[0]);

    xTaskNotifyFromISR((TaskHandle_t)uartTaskHandle,
                       (uint32_t)UART2_EVT,
                       (eNotifyAction)eSetBits,
                       &xHigherPriorityTaskWoken);
    portYIELD_FROM_ISR(xHigherPriorityTaskWoken);
  }
  else
  {
    // pass
  }
}


void parse_cmd(char cmd)
{
  static char info[128] = {'\0'};

  switch (cmd)
  {
  case 'G':
    Flag_Qian = 1, Flag_Hou = 0, Flag_Left = 0, Flag_Right = 0;
    sprintf(info, "\r\nGo ahead\r\n");
    break;
  case 'B':
    Flag_Qian = 0, Flag_Hou = 1, Flag_Left = 0, Flag_Right = 0;
    sprintf(info, "\r\nBackward\r\n");
    break;
  case 'R':
    Flag_Qian = 0, Flag_Hou = 0, Flag_Left = 0, Flag_Right = 1;
    sprintf(info, "\r\nTurn right\r\n");
    break;
  case 'L':
    Flag_Qian = 0, Flag_Hou = 0, Flag_Left = 1, Flag_Right = 0;
    sprintf(info, "\r\nTurn left\r\n");
    break;
  case 'S':
    Flag_Qian = 0, Flag_Hou = 0, Flag_Left = 0, Flag_Right = 0;
    sprintf(info, "\r\nStop\r\n");
    break;

  case '\0':
    // ignore this endle char
    break;
  default:
    sprintf(info, "\r\nUnknown command %c\r\n", cmd);
    break;
  }

  printf(info);
  //HAL_UART_Transmit(&huart2, (uint8_t *)info, strlen(info), 100);

  return;
}

void parse_uart2_cmd(void)
{
  char c;

  c = UART2_Dequeue();
  while (c)
  {
    parse_cmd(c);
    c = UART2_Dequeue();
  }
}

void parse_uart1_cmd(void)
{
  char c;

  c = UART1_Dequeue();
  while (c)
  {
    parse_cmd(c);
    c = UART1_Dequeue();
  }
}

 void uart_task(void *pvParameters)
 {
 	uint32_t NotifyValue;
 	BaseType_t err;
	
 	while(1)
 	{
 		//获取任务通知�??????
 		err=xTaskNotifyWait((uint32_t	)0x00,				//进入函数的时候不清除任务bit
 							(uint32_t	)0xFFFFFFFF,			//�??????出函数的时�?�清除所有的bit
 							(uint32_t*	)&NotifyValue,		//保存任务通知�??????
 							(TickType_t	)portMAX_DELAY);	//阻塞时间
		
 		if(err==pdPASS)	   //任务通知获取成功
 		{
      if ((NotifyValue & UART1_EVT) != 0)
      {
        parse_uart1_cmd();
      }

      if ((NotifyValue & UART2_EVT) != 0)
      {
        parse_uart2_cmd();
      }
    }
    else
 		{
 			printf("任务通知获取失败\r\n");
 		}        
 	}
 }

/* USER CODE END 1 */
